import request from '@/utils/request';
import { requestWrapper, randomInt, randomDate } from '@/utils/mock';

// 获取备份任务列表
export function getBackupList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/backup/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 28; // 模拟总数
      
      // 状态过滤
      const statusFilter = params?.status || '';
      
      // 生成备份任务数据
      const generateBackupTask = (index) => {
        const statuses = ['success', 'fail', 'running'];
        const backupTypes = ['full', 'incremental'];
        const taskNames = [
          '每日备份',
          '每周备份',
          '每月备份',
          '手动备份',
          '上线前备份',
          '紧急备份'
        ];
        
        // 根据传入的状态过滤
        let status = statuses[randomInt(0, statuses.length - 1)];
        if (statusFilter && statuses.includes(statusFilter)) {
          status = statusFilter;
        }
        
        // 生成备份时间（最近30天内）
        const now = new Date();
        const startDate = new Date(now);
        startDate.setDate(now.getDate() - randomInt(0, 30));
        const startTime = startDate.toISOString().split('T')[0] + ' ' + 
                      new Array(3).fill(0).map(() => String(randomInt(0, 23)).padStart(2, '0')).join(':');
        
        // 结束时间（成功/失败的任务有结束时间，运行中的任务没有）
        let endTime = null;
        let duration = null;
        if (status !== 'running') {
          // 结束时间在开始时间1-10分钟后
          const endDate = new Date(startDate);
          const minutes = randomInt(1, 10);
          endDate.setMinutes(endDate.getMinutes() + minutes);
          endTime = endDate.toISOString().split('T')[0] + ' ' + 
                    new Array(3).fill(0).map(() => String(randomInt(0, 23)).padStart(2, '0')).join(':');
          
          // 计算持续时间
          const seconds = minutes * 60 + randomInt(0, 59);
          if (seconds < 60) {
            duration = `${seconds}秒`;
          } else {
            const min = Math.floor(seconds / 60);
            const sec = seconds % 60;
            duration = `${min}分${sec}秒`;
          }
        }
        
        // 生成文件大小（10MB - 500MB）
        const fileSize = `${randomInt(10, 500)}MB`;
        
        return {
          taskId: index + 1,
          taskName: taskNames[randomInt(0, taskNames.length - 1)],
          backupType: backupTypes[randomInt(0, backupTypes.length - 1)],
          fileName: `backup_${startDate.toISOString().split('T')[0].replace(/-/g, '')}.zip`,
          fileSize,
          status,
          startTime,
          endTime,
          duration
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateBackupTask(startIndex + i));
      
      return {
        list,
        total,
        pageNum: parseInt(pageNum),
        pageSize: parseInt(pageSize)
      };
    }
  );
}

// 创建备份任务
export function createBackupTask(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/backup/create',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      taskId: Date.now()
    }
  );
}

// 还原数据
export function restoreData(taskId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/backup/restore/${taskId}`,
      method: 'post'
    }),
    // 模拟数据
    {
      restoreId: Date.now()
    }
  );
}

// 下载备份文件
export function downloadBackup(taskId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/backup/download/${taskId}`,
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据 - 对于下载操作，模拟数据意义不大，但我们提供一个成功响应
    () => new Blob(['Simulated backup file content'], { type: 'application/zip' })
  );
}

// 删除备份
export function deleteBackup(taskIds) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/backup/${taskIds}`,
      method: 'delete'
    }),
    // 模拟数据
    {
      success: true
    }
  );
}

// 获取备份配置
export function getBackupConfig() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/backup/config',
      method: 'get'
    }),
    // 模拟数据
    {
      autoBackup: true,
      backupTime: "02:00",
      backupCycle: "daily",
      keepDays: 30,
      backupPath: "/data/backup",
      compressionLevel: "medium"
    }
  );
}

// 更新备份配置
export function updateBackupConfig(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/backup/config',
      method: 'put',
      data
    }),
    // 模拟数据
    {
      success: true
    }
  );
} 